//
//  BKAttributedString.m
//  XPhoto
//
//  Created by sentinel on 2020/3/25.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "BKAttributedString.h"
#import <BKKit/Theme.h>

@implementation BKAttributedString

+ (NSMutableAttributedString *)attrString:(NSString*)text font:(UIFont*)font color:(UIColor *)color{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    if (font) {
        attrs[NSFontAttributeName] = font;
    }
    if (color) {
        attrs[NSForegroundColorAttributeName] = color;
    }
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]
                                                initWithString:text
                                                attributes:attrs];
    return attrStr;
}
+ (void)setAttributedString:(NSMutableAttributedString*)attributedString withRegexp:(NSString *)regExp withLinkType:(NSString *)linkType{
    NSString *s = attributedString.string;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *arr = [re matchesInString:s options:0 range:NSMakeRange(0, [s length])];
    if (arr && [arr count] > 0) {
        for (NSTextCheckingResult* b in arr){
            NSString *catchedString = [s substringWithRange:[b rangeAtIndex:1]];
            catchedString = [catchedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            NSString *link = catchedString;
            if (![linkType isEqualToString:APP_LINK_TYPE_HTTP]) {
                link = APP_LINK(linkType, catchedString);
            }
            
            [attributedString addAttributes:@{
                NSFontAttributeName:THEME_TEXT_COMMENT_FONT,
                NSForegroundColorAttributeName:THEME_TEXT_LINK_COLOR,
                NSLinkAttributeName:link
            } range:[b rangeAtIndex:0]];
        }
    }
}
@end
